package com.stud.system.controller.tool;

import com.aliyun.oss.model.ObjectListing;
import com.stud.common.core.controller.BaseController;
import com.stud.common.core.domain.Result;
import com.stud.common.enums.FileBusinessType;
import com.stud.common.utils.oss.OssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 阿里 Oss 接口
 *
 * @author Stud
 */
@Api(tags = "Oss接口")
@RestController
@RequestMapping("/tool/oss")
@Slf4j
public class OssController extends BaseController {

    @ApiOperation("判断bucket是否存在")
    @GetMapping("doesBucketExist")
    public Result<Boolean> doesBucketExist() {
        return Result.ok(OssUtil.doesBucketExist());
    }

    @ApiOperation("查询文件列表")
    @GetMapping("listObjects")
    public Result<ObjectListing> listObjects(String prefix, String nextMarker, Integer maxKeys) {
        return Result.ok(OssUtil.listObjects(prefix, nextMarker, maxKeys));
    }

    @ApiOperation("上传")
    @PostMapping("putObject")
    public Result<String> putObject(@RequestParam("file") MultipartFile file, @RequestParam("businessType") FileBusinessType businessType) {
        return Result.ok(OssUtil.putObject(file, businessType));
    }

    @ApiOperation("上传(不按照日期新建目录,文件名会添加后缀防止重名)")
    @PostMapping("uploadObject")
    public Result<String> uploadObject(@RequestParam("file") MultipartFile file, @RequestParam("businessType") FileBusinessType businessType, String fullPath) {
        String fileKey = OssUtil.uploadObject(file, businessType);
        if (Boolean.parseBoolean(fullPath)) {
            return Result.ok(OssUtil.fileKey2Url(fileKey));
        } else {
            return Result.ok(fileKey);
        }
    }

    @ApiOperation("获取文件")
    @GetMapping("getObject")
    public void getObject(@RequestParam String fileKey, HttpServletResponse response) {
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            log.error("文件下载失败");
        }
        OssUtil.getObject(fileKey, outputStream);
    }

    @ApiOperation("获取文件url")
    @GetMapping("generatePresignedUrl")
    public Result<String> generatePresignedUrl(@RequestParam String fileKey) {
        return Result.ok(OssUtil.generatePresignedUrl(fileKey));
    }

    @ApiOperation("获取文件url")
    @GetMapping("fileKey2Url")
    public Result<String> fileKey2Url(@RequestParam String fileKey) {
        return Result.ok(OssUtil.fileKey2Url(fileKey));
    }

    @ApiOperation("预览Base64")
    @GetMapping("showBase64Img")
    public String showBase64Img(@RequestParam String fileKey) {
        return OssUtil.showBase64Img(fileKey);
    }

}
